package com.example.app5.bitmap;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageView;

import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 下载文件模板
 */
public class DownloadTask {
    private static final int THREAD_POOL_SIZE = 5; // 线程池大小
    private static final ExecutorService executorService = Executors.newFixedThreadPool(THREAD_POOL_SIZE);


    /**
     *
     * @param imageUrl  下载图片的地址
     * @param imageView  需要展示的ui控件
     */
    public static void downloadImage( String imageUrl,  ImageView imageView) {
        Runnable task = new Runnable() {
            @Override
            public void run() {
                try {
                    InputStream inputStream = new java.net.URL(imageUrl).openStream();
                    final Bitmap bitmap = BitmapFactory.decodeStream(inputStream);

                    // 在UI线程更新ImageView
                    imageView.post(new Runnable() {
                        @Override
                        public void run() {

                            imageView.setImageBitmap(bitmap);
                        }
                    });

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        };

        // 将任务提交到线程池中
        executorService.execute(task);
    }
}
